package com.jason.service;

import com.jason.api.EmailService;
import com.jason.api.vo.Response;
import com.jason.constant.ResponseConstant;
import com.jason.entity.AuthCode;
import com.jason.mapper.AuthCodeMapper;
import com.jason.util.DateUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.Random;

@Service
public class AuthCodeService {

    @Autowired
    private AuthCodeMapper authCodeMapper;

    @Reference(timeout = 100000)
    private EmailService emailService;

    private final String SUBJECT = "注册验证码";

    private final Integer CODE_VALID_TIME = 10;

    public void generateCode(String email) {
        if (StringUtils.isEmpty(email))
            throw new RuntimeException("请输入邮箱");
        Random random = new Random();
        StringBuilder builder = new StringBuilder();
        for (int index = 0; index < 6; index++) {
            builder.append(random.nextInt(10));
        }
        String code = builder.toString();

        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);
        authCode.setCreatetime(DateUtil.getCurrentDate());
        authCode.setExpiretime(DateUtil.getDateAfterMinutes(authCode.getCreatetime(), CODE_VALID_TIME));
        authCodeMapper.insertSelective(authCode);

        //调用邮件服务发送验证码
        Response response = emailService.sendEmail(email, SUBJECT, code);
        System.out.println("邮件发送成功:" + (response.getCode().intValue() == ResponseConstant.SUCCESS.intValue()));
    }

    public void checkEmailCode(String email, String code) {
        if (StringUtils.isEmpty(email))
            throw new RuntimeException("请输入邮箱");
        if (StringUtils.isEmpty(code))
            throw new RuntimeException("验证码为空");
        AuthCode authCode = authCodeMapper.selectRecentCodeByEmail(email);
        if (ObjectUtils.isEmpty(authCode))
            throw new RuntimeException("该邮箱没有接收过验证码，请确认");
        Date now = DateUtil.getCurrentDate();
        Date expireTime = authCode.getExpiretime();
        if (now.after(expireTime))
            throw new RuntimeException("验证码已经失效");
        if (!code.equals(authCode.getCode()))
            throw new RuntimeException("验证码错误");
    }
}
